<template>
	<div class="bg-color">
		<top-back :title="this.$route.query.title">
			<div slot="rightItem">
				<div class="operation"><img class="open-img" @click="open" src="../assets/img/open.png" /></div>
				<div class="message" v-if="isShow">
					<div class="message-inner">
						<div class="close"><img @click="close" src="../assets/img/close.png" /></div>
						<div class="content" v-html="replaceA(topTitle)"></div>
					</div>
				</div>
			</div>
		</top-back>
		<!-- 分组 -->
		<div v-if="reset">
			<div class="group" v-for="(value,key,index) in typeListObj" :key="index">
				<div class="group-title">{{key | changeKey}}</div>
				<type-data ref="types" v-for="item in value" @eventList="eventList($event)" :isHide="isShowList" :types="item"
				 @resetEvent="resetEvent($event)" :isReset="isResetList" :key="item.id"></type-data>
			</div>
		</div>
		<div v-if="relationLists.length!==0">
			<div class="sub-table" v-for="item in relationLists">
				<div class="group-title have-icon">{{item.name}}
					<div class="icon-out" @click="addTable(item)">
						<van-icon name="add-o" />
					</div>
				</div>
				<!-- 子表功能 -->
				<div v-for="(value,key,index) in tableShowObj">
					<div v-if="key===item.ename">
						<sub-table v-for="(refItem,_index) in value.child" :ref="key" :item="refItem.data" :index_table="_index" :num="refItem.num"
						 :fromId="refItem.fromId" @deletTable="deletTable" @click.native="editTable(refItem.num,refItem.fromId,refItem.type,refItem.title)"></sub-table>
					</div>
				</div>
			</div>
		</div>
		<!-- 点击新建子表 -->
		<add-sub-table v-if="showAddTable" :upDate="upDate" :item="tableItem" :title="title" @addSuessed="addSuessed" @closeAddTable="closeAddTable"
		 @updateTable="updateTable"></add-sub-table>
		<div class="save-bnt" v-show="hideshow">
			<button @click="submit()">提交</button>
			<button v-if="showSave" @click="submit('save')" style="border-left: 1px solid #ffffff;">保存草稿</button>
		</div> 
		
		<div class="seat"></div>
	</div>
</template>

<script>
	import {
		getField,
		getDetail,
		saveForm
	} from '../request/api.js'
	import {
		submit
	} from '@assets/js/submit.js'
	import topBack from '@components/topBar.vue'
	import typeData from '@components/assembly.vue'
	import subTable from '@components/assemblys/subTable.vue'
	import addSubTable from '@components/assemblys/addSubTable.vue'
	import {handleList} from '@assets/js/mixins/handleList.js'
	export default {
		data() {
			return {
				topTitle: '',
				typeListObj: {},
				isShow: false,
				relationLists: [],
				isShowList: [], //传入子元素显示隐藏数组
				isResetList: {}, //传入子元素的刷新
				reset: true,
				docmHeight: document.documentElement.clientHeight || document.body.clientHeight,
				showHeight: document.documentElement.clientHeight || document.body.clientHeight,
				hideshow: true,
				showAddTable: false,
				tableItem: {},
				tableShowList: [],
				tableShowObj: {},
				showSave:true,
				title:'',
				upDate: {
					isEdit: false,
					num: '',
					ename: ''
				}
			}
		},
		mixins:[handleList],
		components: {
			topBack,
			typeData,
			subTable,
			addSubTable
		},
		created() {
			this.$store.commit('setOnce','go')
			if(this.$route.query.num){
				this.request('update',this.$route.query.num)
				// 回显子表
				getDetail({
					'_form': this.$route.query.form_id,
					'_num': this.$route.query.num
				}).then(res=>{
					if(res.code === 0){
						if(res.small_tables){
							this.tableShowList = this.handleList(res.small_tables)					
							this.tableShowObj = this.changeList(this.tableShowList)
						}
					}
				})
			}else{
				this.request('add','')
			}
			if(this.$route.query.type){
				this.showSave = false
			}
			
		},
		computed: {
			replaceA() {
				return function(val) {
					return val.replace(/(<\/?a.*?>)|(<\/?span.*?>)/g, '');
				}
			}
		},
		mounted() {
			//监听事件
			window.onresize = () => {
				return (() => {
					this.showHeight = document.documentElement.clientHeight || document.body.clientHeight;
				})()
			}
		},
		methods: {
			editTable(num, fromId, ename ,title) {
				this.showAddTable = true
				this.upDate.isEdit = true
				this.upDate.num = num
				this.upDate.fromId = fromId
				this.upDate.ename = ename
				this.title = title
			},
			changeAdd() {
				this.upDate.isEdit = false
				this.upDate.num = ''
				this.upDate.fromId = ''
				this.upDate.ename = ''
			},
			closeAddTable() {
				this.showAddTable = false
				this.changeAdd()
			},
			deletTable(arr) {
				this.$axios.post(`/api/delete?_form=${arr[0]}&_num=${arr[1]}`).then(res => {
					if (res.data.code === 0) {
						this.$toast('删除成功')
						this.tableShowList.splice(this.tableShowList.findIndex(e => e.num === arr[1]), 1)
						this.tableShowObj = this.changeList(this.tableShowList)
					} else {
						this.$toast('删除失败')
					}
				})
			},
			updateTable(num) {
				this.showAddTable = false
				this.changeAdd()
				getDetail({
					'_form': num[0],
					'_num': num[1]
				}).then(res => {
					const value = num[2]
					let obj = {
						data: res.formData.fields,
						type: value,
						num: num[1],
						fromId: num[0]
					}
					let _index;
					this.tableShowList.forEach((item, index) => {
						if (item.num === obj.num) {
							_index = index
						}
					})
					this.tableShowList.splice(_index, 1, obj)
					this.tableShowObj = this.changeList(this.tableShowList)
					
				})
			},
			addSuessed(num) { //请求展示子数据
				this.showAddTable = false
				this.changeAdd()
				getDetail({
					'_form': num[0],
					'_num': num[1]
				}).then(res => {
					const value = num[2]
					this.tableShowList.unshift({
						data: res.formData.fields,
						type: value,
						num: num[1],
						fromId: num[0]
					})
					this.tableShowObj = this.changeList(this.tableShowList)
				})
			},
			changeList(list) {
				let obj = {}
				list.forEach((item, index) => {
					let {
						type
					} = item;
					if (!obj[type]) {
						obj[type] = {
							type,
							child: []
						}
					}
					obj[type].child.push(item);
				});
				return obj
			},
			addTable(item) {
				this.showAddTable = true
				this.tableItem = item
				this.title = item.name
			},
			eventList(list) {
				this.isShowList = list
			},
			resetEvent(list) {
				this.isResetList = list
			},
			open() {
				this.isShow = true
			},
			close() {
				this.isShow = false
			},
			refTableCheck(arr) {
				//子表校验
				let list = []
				let isRef
				arr.forEach(item => {
					if (item.isMustFill === '1') {
						list.push({
							ename: item.ename,
							name: item.name
						})
					}
				})
				list.forEach(item => {
					if (this.$refs[item.ename] === undefined) {
						this.$toast(`${item.name}不能为空`);
					}
				})
				let that = this
				isRef = list.every(function(item) {
					return that.$refs[item.ename] !== undefined
				})
				return isRef
			},
			submit(play) {
				const arr = submit(this.$refs.types)
				let obj = arr[1]
				if (this.$store.state._tmpBigId === undefined) {
					this.$store.state._tmpBigId = ''
				}
				const isRef = this.refTableCheck(this.relationLists)
				let saveType,numStr,tmpBigId
				if(this.$route.query.num){
					saveType = 'update'
					numStr = `&_num=${this.$route.query.num}`
					tmpBigId = ''
				}else{
					saveType = 'save'
					numStr = ''
					tmpBigId = `&_tmpBigId=${this.$store.state._tmpBigId}`
				}
				if (arr[0] === true && isRef) {
					if(play !== 'save'){
						this.$axios.post(`/api/${saveType}?_form=${this.$route.query.form_id}${numStr}${tmpBigId}`, obj).then(
							res => {
								if (res.data.code == 0) {
									this.$toast.success('提交成功')
									this.$router.push('/applyuser/apply')
								}
							})
					}else{
						this.$axios.post(`/api/${saveType}?_form=${this.$route.query.form_id}${numStr}${tmpBigId}&_isSaveDraft=1`, obj).then(
							res => {
								if (res.data.code == 0) {
									this.$toast.success('保存成功')
									this.$router.push('/draft')
								}
							})
					}
					
				}
			},
			async request(type,num) {
				let obj = {
					'_form': this.$route.query.form_id,
					'_type': type,
					'_num': num,
				}
				await getField(obj).then(res => {
					if (res.code == 0) {
						this.topTitle = res.fieldGroupsMap['无']
						this.typeListObj = res.fieldMapLists
						this.relationLists = res.relationLists?res.relationLists:[]
						this.$store.commit('setTmpBigId', res._tmpBigId)
					}
				})
			}
		},
		beforeRouteLeave(to, form, next) {
			this.$store.commit('setTmpBigId', '')
			next()
		},
		filters: {
			changeKey(key) {
				if (key === '无') {
					return '业务信息'
				} else {
					return key
				}
			}
		},
		watch: {
			//监听显示高度
			showHeight: function() {
				if (this.docmHeight > this.showHeight) {
					this.hideshow = false
				} else {
					this.hideshow = true
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.operation {
		text-align: right;
	}

	.open-img {
		width: vw(22);
		vertical-align: middle;
		margin-right: vw(12);
	}

	.close {
		text-align: right;
		height: vw(70);
	}

	.close img {
		width: vw(22);
	}

	.message {
		width: 100vw;
		height: 100vh;
		background-color: #FFFFFF;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 5;
		overflow: auto;
	}

	.message-inner {
		margin: 0 auto;
		padding: 0 vw(12);
	}

	.bg-color {
		background-color: $bg-1;
	}
	.save-bnt{
		width: 100vw;
		display: flex;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 2;
	}
	.save-bnt button{
		width: 100%;
		flex: 1;
		height: vw(58);
		border: none;
		background-color: $color4;
		outline: none;
		font-size: vw(18);
		color: #FFFFFF;
		font-weight: 550;		
	}

	.group {
		margin-top: vw(12);
	}

	.group-title {
		font-size: vw(16);
		border-bottom: vw(1) solid $line-1;
		padding: vw(12) vw(12);
		background-color: #FFFFFF;
	}

	.staus-img {
		width: vw(70);
		height: vw(70);
		position: absolute;
		right: vw(10);
		top: 0;
		z-index: 3;
	}

	.steps-out {
		background-color: #FFFFFF;
		margin-top: vw(12);
		padding-top: vw(12);
	}

	.content {
		line-height: vw(48) !important;
		font-size: vw(14);
	}

	.seat {
		width: 100vw;
		height: vw(86);
		background-color: #FFFFFF;
	}

	.sub-table {
		margin-top: vw(15);
	}

	.have-icon {
		// border: none !important;
		position: relative;
	}

	.icon-out {
		overflow: hidden;
		right: 0;
		top: 0;
		width: 14%;
		height: 100%;
		position: absolute;
		color: red;
	}

	.van-icon {
		top: vw(15);
		right: -18px;
		font-size: vw(20);
	}
</style>
